<template>
  <div id="pictureDetailPage">
    <a-row :gutter="[16, 16]">
      <!-- 图片展示区 -->
      <a-col :sm="24" :md="16" :xl="18">
        <a-card title="图片预览">
          <a-image style="max-height: 600px; object-fit: contain" :src="picture.url" />
        </a-card>
      </a-col>
      <!-- 图片信息区 -->
      <a-col :sm="24" :md="8" :xl="6">
        <a-card title="图片信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="作者">
              <a-space>
                <a-avatar :size="24" :src="picture.user?.userAvatar" />
                <div>{{ picture.user?.userName }}</div>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="名称">
              {{ picture.name ?? '未命名' }}
            </a-descriptions-item>
            <a-descriptions-item label="简介">
              {{ picture.introduction ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类">
              {{ picture.category ?? '默认' }}
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in picture.tags" :key="tag">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">
              {{ picture.picFormat ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽度">
              {{ picture.picWidth ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="高度">
              {{ picture.picHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">
              {{ picture.picScale ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ formatSize(picture.picSize) }}
            </a-descriptions-item>
          </a-descriptions>
          <a-space wrap>
            <a-button type="primary" @click="doDownload">
              免费下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
            <a-button v-if="canEdit" type="default" @click="doEdit">
              编辑
              <template #icon>
                <EditOutlined />
              </template>
            </a-button>
            <a-button v-if="canDelete" danger @click="doDelete">
              删除
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-space>
        </a-card>
      </a-col>
      <a-col :sm="24" :md="16" :xl="18">
        <a-card title="评论区">
          <a-list :data-source="comments">
            <template #renderItem="{ item }">
              <comment-item :comment="item" :depth="0" />
            </template>
          </a-list>

          <!-- 根评论输入框 -->
          <a-comment>
            <template #avatar>
              <a-avatar :src="loginUserStore.loginUser?.userAvatar" />
            </template>
            <template #content>
              <a-form-item>
                <a-textarea :rows="4" v-model:value="commentContent" />
              </a-form-item>
              <a-form-item>
                <a-button html-type="submit" :loading="submitting" type="primary" @click="addComment">
                  添加评论
                </a-button>
              </a-form-item>
            </template>
          </a-comment>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, provide, ref } from 'vue'
import { deletePictureUsingPost, getPictureVoByIdUsingGet } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { downloadImage, formatSize } from '@/utils'
import { DeleteOutlined, DownloadOutlined, EditOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { SPACE_PERMISSION_ENUM } from '@/constants/space.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { createCommentUsingPost, getRootCommentsUsingGet } from '@/api/commentController.ts'
import CommentItem from '@/components/CommentItem.vue'

const props = defineProps<{
  id: string
}>()
const picture = ref<API.PictureVO>({})
const router = useRouter()
const comments = ref<API.CommentVO[]>([])
const commentContent = ref('')
const submitting = ref(false)
const loginUserStore = useLoginUserStore()
const parentId = ref<number | undefined>(undefined)
// 提供 localReplyState 给子组件
const localReplyClick = ref(false)
provide('localReplyClick', localReplyClick)
// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      id: props.id
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
    }
  } catch (e) {
    message.error('获取图片详情失败：' + (e as Error).message)
  }
}
// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await getRootCommentsUsingGet({
      pictureId: props.id
    })
    if (res.data.code === 0 && res.data.data) {
      comments.value = res.data.data
    } else {
      message.error('获取评论失败，' + res.data.message)
    }
  } catch (e) {
    message.error('获取评论失败：' + (e as Error).message)
  }
}

// 发布评论
const addComment = async () => {
  if (!commentContent.value) {
    message.warning('请输入评论内容')
    return
  }
  submitting.value = true
  try {
    const res = await createCommentUsingPost({
      pictureId: props.id,
      userId: loginUserStore.loginUser?.id,
      content: commentContent.value,
      parentId: parentId.value // 添加 parentId 参数
    })
    if (res.data.code === 0) {
      message.success('评论成功')
      commentContent.value = ''
      parentId.value = undefined // 重置 parentId
      localReplyClick.value = true // 重置 localReplyClick
      await fetchComments() // 刷新评论列表
    } else {
      message.error('评论失败，' + res.data.message)
    }
  } catch (e) {
    message.error('评论失败：' + (e as Error).message)
  } finally {
    submitting.value = false
  }
}

// 提供响应式变量给子组件
provide('commentContent', commentContent)
provide('submitting', submitting)
provide('parentId', parentId)
provide('refreshComments', fetchComments)
// 编辑
const doEdit = () => {
  router.push({
    path: '/add_picture',
    query: {
      id: picture.value.id,
      spaceId: picture.value.spaceId
    }
  })
}
// 删除
const doDelete = async () => {
  const id = picture.value.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
  } else {
    message.error('删除失败')
  }
}
// 下载图片
const doDownload = () => {
  downloadImage(picture.value.url)
}
onMounted(() => {
  fetchPictureDetail()
  fetchComments() // 加载评论列表
})


// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (picture.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)


</script>

<style scoped></style>
